package com.my.attendance.util;

import com.alibaba.druid.pool.DruidDataSource;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class DBUtil {
    private static DataSource dataSource;

    static {
        try {
            //1.加载properties配置文件
            Properties p = new Properties();
            p.load(DBUtil.class.getResourceAsStream("/jdbc.properties"));
//            p.load(new FileInputStream("jdbc.properties"));
            //2.把配置文件中属性设置连接池中
            DruidDataSource ds = new DruidDataSource();
            ds.configFromPropety(p);
            dataSource=ds;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConn(){
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return conn;
    }

    // 归还连接池
    public static void close(ResultSet rs, PreparedStatement st, Connection conn){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if(st!=null){
            try {
                st.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

}
